﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using HKEA.CMS.Core.BLL;
using HKEA.CMS.Core.Models;
using HKEA.CMS.Core.Utility;
using HKEA.CMS.Core.BLL.Mtbl;
using HKEA.CMS.Core.BLL.Tbl;

namespace WebApplication
{
    public partial class ProductCategory : BasePage
    {
        private static tblCustomer entCust = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string uid = Request.QueryString[Constant.UrlParamName.CustomerUID];
                if (string.IsNullOrEmpty(uid))
                {
                    usermeg.Visible = false;
                    LbtnSave.Enabled = false;
                }
                else
                {
                    usermeg.Visible = true;
                    entCust = new tblCustomer();
                    tblCustomerBLL bll = tblCustomerBLL.GetInstance();
                    entCust.CustomerUID = int.Parse(uid);
                    entCust = bll.GetEntity(entCust);
                }
                CreateProductCategory();
            }
        }

        #region  生成或者绑定 5种大分类 的所有checkbox；

        /// <summary>
        /// 按照Product Category 生成全部的checklist
        /// </summary>
        private void CreateProductCategory()
        {
            List<string> tmp = new List<string>();
            tmp.Add("A"); tmp.Add("B"); tmp.Add("C"); tmp.Add("D"); tmp.Add("E");
            rp_Cate_All.DataSource = tmp;
            rp_Cate_All.DataBind();
        }

        /// <summary>
        /// 生成product category 部分的checklist
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void rp_Cate_All_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            string param = e.Item.DataItem as string;
            CheckBoxList cbl_categoy = e.Item.FindControl("cbl_cate") as CheckBoxList;
            Repeater rp_categoy = e.Item.FindControl("rp_cate") as Repeater;

            mtblProductCatBLL bllProductCate = mtblProductCatBLL.GetInstance();

            if (!string.IsNullOrEmpty(param) && cbl_categoy != null)
            {
                mtblProductCat ent_PC = new mtblProductCat();
                ent_PC.ProductCatID = param;
                List<mtblProductCat> listProductCat = bllProductCate.GetListByENT(ent_PC);
                cbl_categoy.DataSource = listProductCat;

                foreach (mtblProductCat ent in listProductCat)
                {
                    if (ent != null)
                        ent.LastModifyBy = ent.ProductCat_Eng + " " + ent.ProductCat_Chi;
                }

                cbl_categoy.DataTextField = "LastModifyBy";
                cbl_categoy.DataValueField = "ProductCatUID";
                cbl_categoy.DataBind();

                rp_categoy.DataSource = listProductCat;
                rp_categoy.DataBind();
            }
        }

        /// <summary>
        /// 生成 和绑定被选项  product sub category 部分的checklist
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void rp_cate_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            mtblProductCat tmp = e.Item.DataItem as mtblProductCat;
            mtblProductSubCat ent_PSC = new mtblProductSubCat();
            ent_PSC.ProductCatUID = tmp.ProductCatUID;

            List<mtblProductSubCat> listProductSubCat = mtblProductSubCatBLL.GetInstance().GetListByENT(ent_PSC);
            CheckBoxList cbl_subcategoy = e.Item.FindControl("cbl_subcate") as CheckBoxList;

            foreach (mtblProductSubCat ent in listProductSubCat)
            {
                if (ent != null)
                    ent.LastModifyBy = ent.ProductSubCat_Eng + " " + ent.ProductSubCat_Chi;
            }

            if (tmp != null && cbl_subcategoy != null)
            {
                cbl_subcategoy.DataSource = listProductSubCat;
                cbl_subcategoy.DataTextField = "LastModifyBy";
                cbl_subcategoy.DataValueField = "ProductSubCatUID";
                cbl_subcategoy.DataBind();
            }

            ///根据数据绑定选中的项
            if (entCust != null)
            {
                tblCust_ProdCat ent_Cust_ProdCat = new tblCust_ProdCat();
                ent_Cust_ProdCat.CustomerUID = entCust.CustomerUID;
                ent_Cust_ProdCat.Deleted = Constant.IsDelete.no;
                ent_Cust_ProdCat.ProductCatUID = tmp.ProductCatUID;
                List<tblCust_ProdCat> list_Cust_ProdCat = tblCust_ProdCatBLL.GetInstance().GetListByENT(ent_Cust_ProdCat);

                for (int j = 0; j < list_Cust_ProdCat.Count(); j++)
                {
                    for (int i = 0; i < cbl_subcategoy.Items.Count; i++)
                    {

                        if (cbl_subcategoy.Items[i].Value == list_Cust_ProdCat[j].ProductSubCatUID.ToString())
                        {
                            cbl_subcategoy.Items[i].Selected = true;
                            HiddenField_val.Value += cbl_subcategoy.Items[i].Value + ",";
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private List<object> GetCheckValue()
        {
            List<ProductSeq> proSubCateUIDs_check = new List<ProductSeq>();
            List<ProductSeq> proSubCateUIDs_uncheck = new List<ProductSeq>();
            List<object> ret = new List<object>();

            int productCatUID = 0;

            foreach (RepeaterItem tmp in rp_Cate_All.Items)
            {
                Repeater rp = tmp.FindControl("rp_cate") as Repeater;
                if (rp != null)
                {
                    foreach (RepeaterItem tmp1 in rp.Items)
                    {
                        CheckBoxList cbl = tmp1.FindControl("cbl_subcate") as CheckBoxList;
                        HiddenField hdProductCatUID = tmp1.FindControl("hdProductCatUID") as HiddenField;
                        if (cbl != null && hdProductCatUID != null)
                        {
                            productCatUID = int.Parse(hdProductCatUID.Value);
                            for (int i = 0; i < cbl.Items.Count; i++)
                            {
                                if (cbl.Items[i].Selected)
                                {
                                    ProductSeq pseq = new ProductSeq();
                                    pseq.ProductCatUID = productCatUID;
                                    pseq.ProductSubCatUID = int.Parse(cbl.Items[i].Value);
                                    proSubCateUIDs_check.Add(pseq);
                                }
                                else
                                {
                                    ProductSeq pseq = new ProductSeq();
                                    pseq.ProductCatUID = productCatUID;
                                    pseq.ProductSubCatUID = int.Parse(cbl.Items[i].Value);
                                    proSubCateUIDs_uncheck.Add(pseq);
                                }
                            }
                        }
                    }
                }
            }
            ret.Add(proSubCateUIDs_check);
            ret.Add(proSubCateUIDs_uncheck);
            return ret;
        }

        #endregion

        /// <summary>
        /// 保存事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void LbtnSave_Click(object sender, EventArgs e)
        {
            if (entCust != null)
            {
                List<object> ret = GetCheckValue();
                if (ret.Count() == 2)
                {
                    List<ProductSeq> checklist = ret[0] as List<ProductSeq>;
                    List<ProductSeq> unchecklist = ret[1] as List<ProductSeq>;
                    _save(checklist, entCust.CustomerUID);
                    _delete(unchecklist, entCust.CustomerUID);
                    WriteToLog();
                    lblMessages.Text = ResourceManage.GetResourceString("msg100002");
                }
            }
            else
            {
                lblMessages.Text = ResourceManage.GetResourceString("msg100006");
            }
        }

        /// <summary>
        /// 把选中项保存 到数据库表
        /// </summary>
        /// <param name="listProductSubCatUID"></param>
        /// <param name="custUID"></param>
        private void _save(List<ProductSeq> listProductSeq, int custUID)
        {
            tblCust_ProdCatBLL bll = new tblCust_ProdCatBLL();
            for (int i = 0; i < listProductSeq.Count(); i++)
            {
                tblCust_ProdCat tmp = new tblCust_ProdCat();
                tmp.CustomerUID = custUID;
                tmp.Deleted = -1;
                tmp.ProductSubCatUID = listProductSeq[i].ProductSubCatUID;
                List<tblCust_ProdCat> list_tmp = bll.GetListByENT(tmp);
                if (list_tmp.Count() <= 0)//不存在的保存
                {
                    tmp.ProductCatUID = listProductSeq[i].ProductCatUID;
                    tmp.Deleted = Constant.IsDelete.no;
                    tmp.LastModifyBy = Session[Constant.SessionName.Manage] == null ? "system" : (Session[Constant.SessionName.Manage] as tblUser).User_Name.Trim();
                    bll.InsertENT(tmp);
                }
                else//存在的修改 deleted 为0
                {
                    tmp = list_tmp[0];
                    tmp.ProductCatUID = listProductSeq[i].ProductCatUID;
                    tmp.Deleted = Constant.IsDelete.no;
                    tmp.LastModifyBy = Session[Constant.SessionName.Manage] == null ? "system" : (Session[Constant.SessionName.Manage] as tblUser).User_Name.Trim();
                    bll.UpdateENT(tmp);
                }
            }
        }

        private void _delete(List<ProductSeq> listProductSeq, int custUID)
        {
            tblCust_ProdCatBLL bll = new tblCust_ProdCatBLL();
            for (int i = 0; i < listProductSeq.Count(); i++)
            {
                tblCust_ProdCat tmp = new tblCust_ProdCat();
                tmp.CustomerUID = custUID;
                tmp.Deleted = -1;//获取 0 1 的记录
                tmp.ProductSubCatUID = listProductSeq[i].ProductSubCatUID;
                List<tblCust_ProdCat> list_tmp = bll.GetListByENT(tmp);
                if (list_tmp.Count() > 0)//修改操作
                {
                    tmp = list_tmp[0];
                    tmp.ProductCatUID = listProductSeq[i].ProductCatUID;
                    tmp.Deleted = Constant.IsDelete.yes;
                    tmp.LastModifyBy = Session[Constant.SessionName.Manage] == null ? "system" : (Session[Constant.SessionName.Manage] as tblUser).User_Name.Trim();
                    bll.UpdateENT(tmp);
                }
                else
                {
                    tmp.ProductCatUID = listProductSeq[i].ProductCatUID;
                    tmp.Deleted = Constant.IsDelete.yes;
                    tmp.LastModifyBy = Session[Constant.SessionName.Manage] == null ? "system" : (Session[Constant.SessionName.Manage] as tblUser).User_Name.Trim();
                    bll.InsertENT(tmp);
                }
            }
        }

        /// <summary>
        /// 离开事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void LbtnQuit_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/CustomerList.aspx");
        }
        protected void WriteToLog()
        {
            tblUser ent = GetManageFromSession();
            int uid =Convert.ToInt32(Request.QueryString[Constant.UrlParamName.CustomerUID]);
            
            string addlog = string.Empty;
            string dellog = string.Empty;
            mtblProductSubCat entProSubCat = new mtblProductSubCat();
            List<mtblProductSubCat> list = mtblProductSubCatBLL.GetInstance().GetListByENT(entProSubCat);
            string[] add = HiddenFiled_add.Value.Split(',');
            string[] delete = HiddenFiled_del.Value.Split(',');
            if (add.Length > 1 | delete.Length > 1)
            {
                for (int i = 0; i < add.Length - 1; i++)
                {
                    var result = list.Where(a => a.ProductSubCatUID == Convert.ToInt32(add[i])).Select(p => p).ToList();
                    foreach (mtblProductSubCat item in result)
                    {
                        addlog += item.ProductSubCat_Eng + ",";
                    }
                }
                for (int i = 0; i < delete.Length - 1; i++)
                {
                    var result = list.Where(a => a.ProductSubCatUID == Convert.ToInt32(delete[i])).Select(p => p).ToList();
                    foreach (mtblProductSubCat item in result)
                    {
                        dellog += item.ProductSubCat_Eng + ",";
                    }
                }
                if (addlog.Length > 1)
                    addlog = " Add " + addlog.Substring(0, addlog.Length - 1);
                else
                    addlog = "";
                if (dellog.Length > 1)
                    dellog = " Delete " + dellog.Substring(0, dellog.Length - 1);
                else
                    dellog = "";

                tblHistory entlog = new tblHistory();
                Literal CompanyName = usermeg.FindControl("ltlCompanyName_eng") as Literal;
                entlog.HistoryCatUID = 2;
                entlog.HistoryTypeUID = 29;
                entlog.CustomerUID = uid;
                entlog.Cust_MemberUID = 0;
                entlog.ContactPersonUID = 0;
                entlog.History_Detail = ent.User_Name + " {" + CompanyName.Text + "}{ProductCategory}" + addlog + dellog;
                entlog.LastModifyBy = ent.User_Name;
                int tal = tblHistoryBLL.GetInstance().InsertENT(entlog);
            }
        }

    }

    class ProductSeq
    {
        public int ProductCatUID
        {
            get;
            set;
        }
        public int ProductSubCatUID
        {
            get;
            set;
        }
    }


}